using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using shuju_jiange.Com;
using System.ComponentModel;
using Microsoft.Office.Interop.Excel;
using Application = System.Windows.Forms.Application;
using System.Threading;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms.DataVisualization.Charting;

namespace shuju_jiange
{
    public partial class Form1 : Form
    {
        private const string strValueSettingFileName = "ValueSetting.dat";
        private FrmShowTotal frmShowTotal = null;
        private bool isGroupMode = false;
        private int groupNum = 0;
        public DataList datalist;
        private int MaxCount = 0;
        private bool isAutoStatMode = false;
        // 用于临时保存第一次统计后的数据
        private Dictionary<string, double> autoStatFirstData = null;
        // 记录每次删除数据在排序后的位置
        private List<int> autoStatDeletedIndexList = new List<int>();
        private Dictionary<int, string> delDatas = new Dictionary<int, string>();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            RefreshValueSetting();
            dataGridView1.Columns.Clear();
            dataGridView1.AutoGenerateColumns = false;
            
            // Add context menu to column headers
            dataGridView1.ColumnHeaderMouseClick += DataGridView1_ColumnHeaderMouseClick;
            
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "ID", Name = "Id", DataPropertyName = "Id" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "%总和", DataPropertyName = "Total" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "数据", DataPropertyName = "SrcData" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "出现次数", Name = "Time", DataPropertyName = "Time" });
            // 在出现次数列后面增加理论间隔列
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "理论间隔", Name = "TheoreticalInterval", DataPropertyName = "TheoreticalInterval" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "次数平均间隔", DataPropertyName = "Blue" });
            // 在次数平均间隔列后面增加Z值列
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "Z值", Name = "ZValue", DataPropertyName = "ZValue" });
           
            //dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "占有率差值", DataPropertyName = "ChaZhi" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "数据平均间隔", Name = "Interval", DataPropertyName = "Interval" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "数据末端差", Name = "DataEndDiff", DataPropertyName = "DataEndDiff" });
            // 新增: 差%（紧跟数据末端差）
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "差%", Name = "Difference_percent", DataPropertyName = "Difference_percent" });
            // 在数据末端差列后面增加新数据间隔Y和新末端差X列
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "新数据间隔Y", Name = "NewDataIntervalY", DataPropertyName = "NewDataIntervalY" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "新末端差X", Name = "NewEndDiffX", DataPropertyName = "NewEndDiffX" });
            // 新增: 新差%（紧跟新末端差X）
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "新差%", Name = "NewDifference_percent", DataPropertyName = "NewDifference_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()
            {
                HeaderText = "偏移数据",
                Name = "Deviation",
                DataPropertyName = "DeviationString"
            });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "值相加", DataPropertyName = "Sum" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "值相加%", DataPropertyName = "Sum_percent" });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "次数差", DataPropertyName = "Cha" });
            // 在次数差列后面增加差值列
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "差值", Name = "DiffValue", DataPropertyName = "DiffValue" });
            // 添加列X列
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "列X", Name = "ColumnX", DataPropertyName = "ColumnX" });
            // 添加数据出现次数列
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "次数对应的数据量", Name = "DataCount", DataPropertyName = "DataCount" });
            // 添加列X2列
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "列X2", Name = "ColumnX2", DataPropertyName = "ColumnX2" });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "占有率", DataPropertyName = "Zhanyoulv" });

           

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A", DataPropertyName = "Ac" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A%", DataPropertyName = "Ac_percent" });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "H", DataPropertyName = "H" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "H%", DataPropertyName = "H_percent" });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B", DataPropertyName = "Bg" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B%", DataPropertyName = "Bg_percent" });


            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "AAC2", DataPropertyName = "AAc2" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "AAC2%", DataPropertyName = "AAc2_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "ACH2", DataPropertyName = "Ach2" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "ACH2%", DataPropertyName = "Ach2_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "ABG2", DataPropertyName = "ABg2" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "ABG2%", DataPropertyName = "ABg2_percent" });



            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "BAC2", DataPropertyName = "BAc2" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "BAC2%", DataPropertyName = "BAc2_percent" });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "BGH2", DataPropertyName = "Bgh2" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "BGH2%", DataPropertyName = "Bgh2_percent" });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "BBG2", DataPropertyName = "BBg2" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "BBG2%", DataPropertyName = "BBg2_percent" });

          
            

           
          



            //dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "BGH3", DataPropertyName = "Bgh3" });
            //dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "BGH3%", DataPropertyName = "Bgh3_percent" });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A1", DataPropertyName = "A1" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A1%", DataPropertyName = "A1_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A2", DataPropertyName = "A2" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A2%", DataPropertyName = "A2_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A3", DataPropertyName = "A3" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A3%", DataPropertyName = "A3_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A4", DataPropertyName = "A4" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A4%", DataPropertyName = "A4_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A5", DataPropertyName = "A5" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A5%", DataPropertyName = "A5_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A6", DataPropertyName = "A6" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "A6%", DataPropertyName = "A6_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B1", DataPropertyName = "B1" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B1%", DataPropertyName = "B1_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B2", DataPropertyName = "B2" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B2%", DataPropertyName = "B2_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B3", DataPropertyName = "B3" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B3%", DataPropertyName = "B3_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B4", DataPropertyName = "B4" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B4%", DataPropertyName = "B4_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B5", DataPropertyName = "B5" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B5%", DataPropertyName = "B5_percent" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B6", DataPropertyName = "B6" });
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "B6%", DataPropertyName = "B6_percent" });


            dataGridView1.Columns[1].DefaultCellStyle.BackColor = Color.LightBlue;

            // 初始化排序列下拉框
            InitializeSortColumnComboBox();
            
            btnStartAutoStat.Enabled = false;
            labelAutoStatCount.Enabled = false;
            textBoxAutoStatCount.Enabled = false;
            btnShowAutoStatPic.Enabled = false;

            // 启动时统计355
            //Count355Rows();
        }
        
        private void InitializeSortColumnComboBox()
        {
            cbSortColumn.Items.Clear();
            // 添加所有可能的排序列，使用与DataGridView列标题一致的名称
            cbSortColumn.Items.AddRange(new string[] {
                "%总和", "数据", "出现次数", "理论间隔", "次数平均间隔", "Z值", "数据平均间隔", "数据末端差", "新数据间隔Y", "新末端差X", "偏移数据", "值相加", "值相加%",
                "次数差", "差值", "列X", "数据出现次数", "列X2", "占有率", "A", "A%", "H", "H%", "B", "B%",
                "AAC2", "AAC2%", "ACH2", "ACH2%", "ABG2", "ABG2%",
                "BAC2", "BAC2%", "BGH2", "BGH2%", "BBG2", "BBG2%",
                "A1", "A1%", "A2", "A2%", "A3", "A3%", "A4", "A4%", "A5", "A5%", "A6", "A6%",
                "B1", "B1%", "B2", "B2%", "B3", "B3%", "B4", "B4%", "B5", "B5%", "B6", "B6%"
            });
            cbSortColumn.SelectedIndex = 0; // 默认选择%总和
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> strlist = new List<string>();
            openFileDialog1.Filter = "csv文件|*.csv";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string file = openFileDialog1.FileName;
                label1.Text = "文件:" + file;
                FileStream fsr = new FileStream(file, FileMode.Open);
                StreamReader sr = new StreamReader(fsr, Encoding.Default);
                strlist.Clear();
                MaxCount = 0;
                string l;
                sr.ReadLine();
                while ((l = sr.ReadLine()) != null)
                {
                    l = l.Replace(",", "").Replace(" ", "");
                    if (l.Contains("*") || l.Length != 3) continue;
                    strlist.Add(l);
                }
                sr.Close();
                fsr.Close();
                richTextBox1.Text = string.Join(" ", strlist);
                MaxCount = strlist.Count;
                labelMax.Text = "导入总记录数:" + MaxCount;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.isGroupMode = false;
            daoru_process(richTextBox1.SelectedText.Trim().Split(' '));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 导出
            saveFileDialog1.Filter = "csv文件|*.csv";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string file = saveFileDialog1.FileName;
                File.Delete(file);
                FileStream fsw = new FileStream(file, FileMode.Create);
                StreamWriter sw = new StreamWriter(fsw, Encoding.Default);
                DataList list = dataGridView1.DataSource as DataList;
                if (list == null)
                {
                    return;
                }
                if (!this.isGroupMode)
                {
                    sw.WriteLine("*,*,*");
                }
                else
                {
                    string[] v = new string[this.groupNum];
                    for (int i = 0; i < v.Length; i++)
                    {
                        v[i] = "*";
                    }
                    sw.WriteLine(string.Join(",", v));
                }                
                for (int i = 0; i < list.Count; i++)
                {
                    if (!this.isGroupMode)
                    {
                        string t = list[i].SrcData;
                        for (int j = 0; j < list[i].Time; j++)
                            sw.WriteLine(string.Join(",",t.ToCharArray()));
                    }
                    else
                    {
                        string[] d = list[i].SrcData.Split('-');
                        for (int j = 0; j < d.Length; j++)
                        {
                            sw.WriteLine(string.Join(",", d));
                        }
                    }
                }
                sw.Close();
                fsw.Close();
                MessageBox.Show("导出成功!");
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.isGroupMode = false;
            daoru_process(richTextBox1.Text.Trim().Split(' '));
            //Count355Rows(); // 导入全部后统计355
        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.isGroupMode = false;
            string str = textBox1.Text.Trim().Replace(' ', '|').Replace(" ", "").Trim().Trim('|');
            daoru_process(str.Split('|'));
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (this.datalist != null && this.datalist.Count>0)
            {
                this.datalist.Clear();
                this.showData(this.datalist);
               // this.ShuaxinLv();
            }
        }


        public class TimeGroup
        {
            public int Time { get; set; }
            public List<mypoint> Points { get; set; }

            public TimeGroup(int time)
            {
                Time = time;
                Points = new List<mypoint>();
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //List<mypoint> pointlist = new List<mypoint>();
            //for (int i = 0; i < this.datalist.Count; i++)
            //{
            //    pointlist.Add(new mypoint(i, this.isGroupMode ? "0" : this.datalist[i].SrcData));
            //}
            //Form2 fm = new Form2(pointlist);
            //fm.ShowDialog();

            List<mypoint> pointlist = new List<mypoint>();
            if (this.datalist == null)
            {
                MessageBox.Show("请加载数据");
                return;
            }

            // 根据time分组并计算平均值
            var groupedData = this.datalist.GroupBy(item => item.Time);
            foreach (var group in groupedData)
            {
                double sum = 0;
                foreach (var item in group)
                {
                    int temp;
                    int.TryParse(item.Interval.ToString(), out temp);
                    sum += temp;
                }
                double average = sum / group.Count();

                // 使用当前group的Time作为x值
                int xValue = group.Key;
                int redValue =Convert.ToInt32( MaxCount/(xValue+1));

                // 获取该组的X、Y、Z和理论间隔-Z值（取第一个元素的值，因为同组的值应该相同）
                var firstItem = group.First();
                float xVal = firstItem.NewEndDiffX;
                float yVal = firstItem.NewDataIntervalY;
                float zVal = firstItem.ZValue;
                float theoreticalMinusZ = firstItem.TheoreticalInterval - firstItem.ZValue;

                pointlist.Add(new mypoint(xValue, Convert.ToInt32(average).ToString(), redValue, xVal, yVal, zVal, theoreticalMinusZ));
            }

            Form2 fm = new Form2(pointlist, chbChazhi.Checked);
            fm.ShowDialog();


        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count < 1)
            {
                MessageBox.Show("没有选中任何行!");
                return;
            }
            DataList list = dataGridView1.DataSource as DataList;            
            if (list == null)
            {
                return;
            }
            List<Data> selectDataRows = new List<Data>();
            List<string> selectStrings = new List<string>();
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                if(row.DataBoundItem is Data)
                {
                    selectDataRows.Add(row.DataBoundItem as Data);
                    selectStrings.Add((row.DataBoundItem as Data).SrcData);
                }
            }
            DialogResult res = MessageBox.Show("请确认是否删除"+ selectDataRows.Count.ToString() + "条数据。", "提示",MessageBoxButtons.YesNo);
            if(res == DialogResult.Yes)
            {
                dataGridView1.DataSource = null;
                DataList removeList2 = new DataList();
                foreach (Data row in selectDataRows)
                {
                    list.Remove(row);
                    MaxCount--;
                    if (!cbshowrepeat.Checked)
                    {
                        foreach (Data data2 in this.datalist)
                        {
                            if (row.SrcData == data2.SrcData && !removeList2.Contains(data2))
                            {
                                removeList2.Add(data2);
                            }
                        }
                    }
                }
                
                for (int j = removeList2.Count - 1; j >= 0; j--)
                {
                    this.datalist.Remove(removeList2[j]);
                }
                this.showData(list);
                richTextBox2.Text += string.Join(" ", selectStrings.ToArray()) + " ";
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            string[] its = textBox2.Text.Trim().Replace(' ', '-').Split('-');
            DataList list = dataGridView1.DataSource as DataList;
            dataGridView1.DataSource = null;
            if (list == null)
            {
                return;
            }
            DataList removeList = new DataList();
            List<string> delStrs = new List<string>();
            foreach (string t in its)
            {
                int value;
                if (int.TryParse(t, out value))
                {
                    for (int i= 0;i < list.Count;i++)
                    {
                        if (list[i].Time == value && !removeList.Contains(list[i]))
                        {
                            delStrs.Add(list[i].SrcData);
                            removeList.Add(list[i]);
                        }
                    }
                }
            }
            for(int j= removeList.Count-1; j >= 0; j--)
            {
                list.Remove(removeList[j]);
            }
            if (!cbshowrepeat.Checked)
            {
                DataList removeList2 = new DataList();
                foreach (Data data in removeList)
                {
                    foreach(Data data2 in this.datalist)
                    {
                        if(data.SrcData == data2.SrcData && !removeList2.Contains(data2))
                        {
                            removeList2.Add(data2);
                        }
                    }
                }
                for (int j = removeList2.Count - 1; j >= 0; j--)
                {
                    this.datalist.Remove(removeList2[j]);
                }
            }
            this.showData(list);
            richTextBox2.Text += string.Join(" ",delStrs.ToArray()) + " ";
        }

       

        private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
            string[] t = richTextBox1.SelectedText.Trim().Split(' ');
            int k = t.Length;
            if (t[0] == "") k = 0;
            label4.Text = "选中记录数为:" + k;


            string[] t1 = richTextBox1.Text.Trim().Split(' ');
            int k1 = t1.Length;
            if (t1[0] == "") k1 = 0;
            labelMax.Text = "当前总记录数:" + k1;//.Text = "选中记录数为:" + k1;
            MaxCount = k1;

        }

        private void button10_Click(object sender, EventArgs e)
        {
            string[] its = textBox3.Text.Trim().Replace(' ', '-').Split('-');
            DataList list = dataGridView1.DataSource as DataList;
            dataGridView1.DataSource = null;
            if (list == null)
            {
                return;
            }
            DataList removeList = new DataList();
            List<string> delStrs = new List<string>();
            foreach (string t in its)
            {
                foreach (Data data in list)
                {
                    if (data.SrcData == t)
                    {
                        delStrs.Add(data.SrcData);
                        removeList.Add(data);
                    }
                }
            }
            foreach (Data data in removeList)
            {
                if (list.Contains(data)) list.Remove(data);
            }
            if (!cbshowrepeat.Checked)
            {
                DataList removeList2 = new DataList();
                foreach (Data data in removeList)
                {
                    foreach (Data data2 in this.datalist)
                    {
                        if (data.SrcData == data2.SrcData && !removeList2.Contains(data2))
                        {
                            removeList2.Add(data2);
                        }
                    }
                }
                for (int j = removeList2.Count - 1; j >= 0; j--)
                {
                    this.datalist.Remove(removeList2[j]);
                }
            }
            this.showData(list);            
            richTextBox2.Text += string.Join(" ", delStrs.ToArray()) + " ";
        }

        private void button11_Click(object sender, EventArgs e)
        {
            string[] its = richTextBox1.Text.Trim().Split(' ');
            int start = its.Length - Convert.ToInt32("0" + textBox5.Text.Trim());
            int end = its.Length - Convert.ToInt32("0" + textBox4.Text.Trim());
            start = (start < 0) ? 0 : start;
            end = (end < 0) ? 0 : end;
            end = (end >= its.Length) ? its.Length-1 : end;
            
            string temp = "";
            for (int i = start; i <= end; i++)
            {
                temp += its[i] + " ";
            }
            this.isGroupMode = false;
            daoru_process(temp.Trim().Split(' '));
        }

        private void button12_Click(object sender, EventArgs e)
        {
            string[] delits = textBox6.Text.Trim().Replace(" ", "|").Split('|');
            string content = richTextBox1.Text.Trim();

            foreach (string s in delits)
            {
                string ks = s.Trim();
                if (ks.Length == 3)
                {
                    content = content.Replace(ks, "");
                }
            }
            content = content.Replace("  ", " ");
            richTextBox1.Text = content;
        }

        private void button13_Click(object sender, EventArgs e)
        {
            string filename = Application.StartupPath + "//main_data.txt";

            File.Delete(filename);
            FileStream fs = new FileStream(filename, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            if (!this.isGroupMode)
            {
                sw.WriteLine("序号,次数,第1位,第2位,第3位");
            }
            else
            {
                string s  = "序号,次数";
                for (int i = 0; i < this.groupNum; i++)
                {
                    s += ",第"+(i+1)+ "位";
                }
                sw.WriteLine(s);
            }
            
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                Data data = dataGridView1.Rows[i].DataBoundItem as Data;
                if(data== null)
                {
                    continue;
                }
                string line = data.SrcData + ",0," + data.DeviationString.Replace("-", ",");
                sw.WriteLine(line);
            }

            sw.Close();
            fs.Close();
            MessageBox.Show("导出成功!");
        }

        private void button14_Click(object sender, EventArgs e)
        {
            daochu_x("pre", checkBox1.Checked);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            daochu_x("next", checkBox1.Checked);
        }

        private void button16_Click(object sender, EventArgs e)
        {
            daochu_x("null", checkBox1.Checked);
        }

        private void daochu_x(string type, bool check)
        {
            string file = "";
            if (check)
                saveFileDialog1.Filter = "csv文件|*.csv";
            else
                saveFileDialog1.Filter = "txt文件|*.txt";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                file = saveFileDialog1.FileName;
            }
            else
            {
                return;
            }
            if (File.Exists(file)) File.Delete(file);
            FileStream fsw = new FileStream(file, FileMode.Create);
            StreamWriter sw = new StreamWriter(fsw, Encoding.Default);

            // ------------------------
            string[] its = richTextBox1.Text.Trim().Split(' ');
            int start = its.Length - Convert.ToInt32("0" + textBox5.Text.Trim());
            int end = its.Length - Convert.ToInt32("0" + textBox4.Text.Trim());
            string t = "", s;
            for (int i = start; i <= end; i++)
            {
                //temp += its[i] + " ";
                if (type == "pre")
                {
                    t = its[i];
                    s = t.Substring(0, 1) + "-1" + t.Substring(1, 1) + "-2" + t.Substring(2, 1);
                }
                else if (type == "next")
                {
                    t = its[end - (i - start)];
                    s = t.Substring(0, 1) + "-1" + t.Substring(1, 1) + "-2" + t.Substring(2, 1);
                }
                else
                {
                    s = its[i];
                }
                if (check)
                    s = s.Replace("|", ",");
                if (type == "null")
                {
                    if (check)
                        sw.Write(s + ",");
                    else
                        sw.Write(s + " ");
                }
                else sw.WriteLine(s);
            }

            // ---------------------
            sw.Close();
            fsw.Close();
            MessageBox.Show("导出完成！");
        }
        void Panel1Paint(object sender, PaintEventArgs e)
        {

        }
        void Button17Click(object sender, EventArgs e)
        {
            textBox6.Text = "";
        }

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 值相加设定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnValueSetting_Click(object sender, EventArgs e)
        {
            Form frm = new FrmValueSetting();
            DialogResult res = frm.ShowDialog();
            if (res == DialogResult.OK)
            {
                RefreshValueSetting();
            }
        }
        /// <summary>
        /// 刷新值相加 下拉框数据
        /// </summary>
        private void RefreshValueSetting()
        {
            // 读取值相加
            List<string> ValueSettings = new List<string>();
            string strValueSettingFilePath = Application.StartupPath + "//" + strValueSettingFileName;
            if (File.Exists(strValueSettingFilePath))
            {
                try
                {
                    string[] strValueSettings = File.ReadAllLines(strValueSettingFilePath);
                    ValueSettings.AddRange(strValueSettings);
                }
                finally
                {

                }
            }
            // 加载到下拉框
            string valueSetting = (string)cbValueSetting.SelectedItem;
            cbValueSetting.Items.Clear();
            ValueSettings.Insert(0, "");
            cbValueSetting.Items.AddRange(ValueSettings.ToArray<string>());

            if (valueSetting != null && cbValueSetting.Items.Contains(valueSetting))
            {
                cbValueSetting.SelectedItem = valueSetting;
            }
            else
            {
                cbValueSetting.SelectedIndex = 0;
            }
        }

        private void btnCountTotal_Click(object sender, EventArgs e)
        {
            // 取得选中值相加
            if (cbValueSetting.SelectedItem == null)
            {
                MessageBox.Show("选中值相加为空，请重新选择", "提示");
                return;
            }
            DataList list = dataGridView1.DataSource as DataList;
            if (list == null)
            {
                return;
            }
            this.showData(list);
        }
               

        private void btnExportMDB_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count != 1)
            {
                MessageBox.Show("请选中一行作为中心位置", "提示");
                return;
            }
            string mdb_file_model_out = Application.StartupPath + "//out_tpl.mdb";
            savefile.Filter = "mdb|*.mdb";
            if (savefile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    File.Delete(savefile.FileName);
                    File.Copy(mdb_file_model_out, savefile.FileName);
                    Database.close_db();
                    Database.init_db(savefile.FileName);
                    string sql_pre = "insert into mytable(id,d1,d2,d3,AC,ACH2,H,AC2,BG2,H2,H3) values";
                    string sql = "";
                    int center = dataGridView1.SelectedRows[0].Index;
                    int maxstep = (dataGridView1.RowCount-center>center) ?dataGridView1.RowCount - center: center;
                    int step = 0;
                    int index = 0;
                    while (step>=(-1)*maxstep && step<=maxstep)
                    {
                        int i = center + step;
                        if (i >= 0 && i < dataGridView1.RowCount)
                        {

                            try
                            {
                                Data data = dataGridView1.Rows[i].DataBoundItem as Data;
                                if (data != null)
                                {
                                    index++;
                                    sql = sql_pre + "(" + index + ", ";
                                    int[] d = data.Deviation.ToArray();
                                    if (d.Length >= 3)
                                    {
                                        sql += d[0].ToString() + ",";
                                        sql += d[1].ToString() + ",";
                                        sql += d[2].ToString() + ",";
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                    sql += data.Ac.ToString() + ",";
                                    sql += data.Ach2.ToString() + ",";
                                    sql += data.H.ToString() + ",";
                                    sql += data.BAc2.ToString() + ",";
                                    sql += data.BBg2.ToString() + ",";
                                    sql += data.Bgh2.ToString() + ",";
                                    sql += data.Bgh3.ToString() + ",";
                                    sql = sql.TrimEnd(',') + ")";
                                    if (data.SrcData.ToString().Trim() != "")
                                    {
                                        Database.run_excute(sql);
                                    }
                                }
                            }
                            catch { }
                        }
                        step = (step >= 0) ? -step - 1 : -step;
                    }
                    Database.close_db();
                    MessageBox.Show("保存成功！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void btnExportCSV_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count != 1)
            {
                MessageBox.Show("请选中一行作为中心位置", "提示");
                return;
            }
            savefile.Filter = "csv文件|*.csv";
            if (savefile.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (File.Exists(savefile.FileName)) File.Delete(savefile.FileName);
                    FileStream fsw = new FileStream(savefile.FileName, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fsw, Encoding.Default);
                    if (!this.isGroupMode)
                    {
                        sw.WriteLine("*,*,*");
                    }else
                    {
                        string[] v = new string[this.groupNum];
                        for (int i= 0; i< v.Length;i++)
                        {
                            v[i] = "*";
                        }
                        sw.WriteLine(string.Join(",",v));
                    }
                    int center = dataGridView1.SelectedRows[0].Index;
                    int maxstep = (dataGridView1.RowCount - center > center) ? dataGridView1.RowCount - center : center;
                    int step = 0;
                    while (step >= (-1) * maxstep && step <= maxstep)
                    {
                        int i = center + step;
                        if (i >= 0 && i < dataGridView1.RowCount)
                        {
                            string s = "";
                            if (!this.isGroupMode)
                            {
                                Data data = dataGridView1.Rows[i].DataBoundItem as Data;
                                if (data != null)
                                {
                                    s += string.Join(",", data.SrcData.ToCharArray());
                                }
                            }
                           else
                            {
                                Data data = dataGridView1.Rows[i].DataBoundItem as Data;
                                if (data != null)
                                {
                                    s += string.Join(",", data.SrcData.Split('-'));
                                }
                            }
                            sw.WriteLine(s);
                        }
                        step = (step >= 0) ? -step - 1 : -step;
                    }

                    sw.Close();
                    fsw.Close();
                    MessageBox.Show("导出完成！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// 显示图形（总和%）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnShowPic_Click(object sender, EventArgs e)
        {
            if (frmShowTotal != null)
            {
                frmShowTotal.Close();
            }
            frmShowTotal = new FrmShowTotal();
            frmShowTotal.Data.Clear();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                try
                {
                    Console.Write(DateTime.Now.Millisecond);
                    Console.Write("\t");
                    Data data = dataGridView1.Rows[i].DataBoundItem as Data;
                    if (data != null)
                    {
                        if(!frmShowTotal.Data.ContainsKey(data.SrcData)) frmShowTotal.Data.Add(data.SrcData, data.Total);
                    }
                    Console.Write("\n");
                }
                catch (Exception ex)
                {
                    Console.Write(ex);
                }
            }
            frmShowTotal.Show();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (frmShowTotal != null)
            {
                frmShowTotal.Close();
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in this.dataGridView1.Rows)
                {
                    row.HeaderCell.Value = (row.Index + 1).ToString();
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
        }

        private void btnGroupImprot_Click(object sender, EventArgs e)
        {
            string group = cbGroup.SelectedItem as string;
            int num;
            string[] its = richTextBox1.Text.Trim().Split(' ');
            if (group!= null  && int.TryParse(group,out num) && num>=2 && its.Length >= 2 * num-1)
            {
                List<string> temp = new List<string>();
                int loop = 2;
                do {
                    int start = its.Length - loop * num + 1;
                    int end = its.Length - (loop-1) * num;
                    string[] values = new string[num];
                    Array.Copy(its,start,values, 0, num);
                    temp.Add(string.Join("-", values));
                    loop++;
                } while (its.Length - loop * num + 1 >=0);
                this.isGroupMode = true;
                this.groupNum = num;
                daoru_process(temp.ToArray());
            }
        }

        private void cbshowrepeat_CheckedChanged(object sender, EventArgs e)
        {
            DataList list = null;
            if (this.datalist != null && this.datalist.Count > 0)
            {
                if (!this.cbshowrepeat.Checked)
                {
                    TypeDescriptor.GetProperties(typeof(Data));
                    this.datalist.Sort(TypeDescriptor.GetProperties(typeof(Data))["Id"], ListSortDirection.Ascending);
                    list = this.datalist.MergeSrcData();
                }
                else
                {
                    list = this.datalist;
                }
                this.showData(list);
            }
        }

        //导入全部数据到表格
        private void daoru_process(string[] datas)
        {
            if(datas == null)
            {
                datas =new string[] { };
            }
            // 更新MaxCount为当前数据的实际长度
            MaxCount = datas.Length;
            labelMax.Text = "导入总记录数:" + MaxCount;
            
            // 同步原始数据到Data静态属性，保证DataEndDiff正确
            Data.CurrentRawDataList = datas.ToList();
            richTextBox2.Text = "";
            this.datalist = new DataList();
            Data.Seed = 1;
            for (int i = 0; i < datas.Length; i++)
            {
                if (string.Empty.Equals(datas[i])) continue;
                this.datalist.Add(new Data()
                {
                    SrcData = datas[i],
                    OwerList = this.datalist,
                    Maxlen = MaxCount
                }); ;
            }
            this.datalist.CountingInterval();
           
            //增加datalist中的其他数据
            var groupedData = this.datalist.GroupBy(item => item.Time);
            foreach (var group in groupedData)
            {
                double sum = 0;
                foreach (var item in group)
                {
                    int temp;
                    int.TryParse(item.Interval.ToString(), out temp);
                    sum += temp;
                }
                double average = sum / group.Count();

                // 使用当前group的Time作为x值
                int xValue = group.Key;
                int redValue = Convert.ToInt32(MaxCount / (xValue + 1));
                // 在 group 中的每个元素中设置 Blue 属性，并同时更新 this.datalist 中的相应元素
                for (int i = 0; i < group.Count(); i++)
                {
                    var currentItem = group.ElementAt(i);
                    var a = Convert.ToInt32(average);
                    currentItem.Blue = a;

                    // 更新 this.datalist 中的相应元素
                    var indexToUpdate = this.datalist.IndexOf(currentItem);
                    if (indexToUpdate != -1)
                    {
                        int cha = redValue - a;
                        this.datalist[indexToUpdate].Red = redValue;
                        this.datalist[indexToUpdate].Blue = a;
                        if (this.datalist[indexToUpdate].Time == 1)
                        {
                            this.datalist[indexToUpdate].Cha = 0;
                        }
                        else
                        {
                            this.datalist[indexToUpdate].Cha = cha;
                        }
                       
                        float zhanyoulv = 0;

                        var shijizhi = 0f;
                        var jisuanzhi = 0f;

                        //if (this.datalist[indexToUpdate].SrcData == "156")
                        //{
                        //    var aa = 0;
                        //}

                        if (this.datalist[indexToUpdate].Interval != 0)
                        {
                            shijizhi = Convert.ToSingle(this.datalist[indexToUpdate].ChaZhi) / Convert.ToSingle(this.datalist[indexToUpdate].Interval);
                            jisuanzhi = Convert.ToSingle(this.datalist[indexToUpdate].ChaZhi) / Convert.ToSingle(this.datalist[indexToUpdate].Blue);
                            var jisuancha = Math.Abs(jisuanzhi - shijizhi);

                            if (shijizhi > jisuanzhi)//如果实际值>计算值
                            {
                                zhanyoulv = shijizhi != 0 ? shijizhi - jisuancha * (jisuancha / shijizhi) : 0;
                            }
                            else
                            {
                                zhanyoulv = shijizhi != 0 ? shijizhi + jisuancha * (jisuancha / shijizhi) : 0;
                            }
                        }
                       
                        this.datalist[indexToUpdate].Zhanyoulv = (zhanyoulv*100);


                    }
                }
               
                // pointlist.Add(new mypoint(xValue, Convert.ToInt32(average).ToString(), redValue));
            }

        
            if (!this.cbshowrepeat.Checked)
            {
                list = this.datalist.MergeSrcData();
            }
            else
            {
                list = this.datalist;
            }

            // 计算新的统计值
            CalculateNewStatistics();

            this.showData(list);
            
            // 数据导入完成后更新X2平均值
            UpdateX2Average();
        }

        public DataList list = null;
        public void ShuaxinLv()
        {
            //增加datalist中的其他数据
            var groupedData = this.datalist.GroupBy(item => item.Time);
            foreach (var group in groupedData)
            {
                double sum = 0;
                foreach (var item in group)
                {
                    int temp;
                    int.TryParse(item.Interval.ToString(), out temp);
                    sum += temp;
                }
                double average = sum / group.Count();

                // 使用当前group的Time作为x值
                int xValue = group.Key;
                int redValue = Convert.ToInt32(MaxCount / (xValue + 1));
                // 在 group 中的每个元素中设置 Blue 属性，并同时更新 this.datalist 中的相应元素
                for (int i = 0; i < group.Count(); i++)
                {
                    var currentItem = group.ElementAt(i);
                    var a = Convert.ToInt32(average);
                    currentItem.Blue = a;

                    // 更新 this.datalist 中的相应元素
                    var indexToUpdate = this.datalist.IndexOf(currentItem);
                    if (indexToUpdate != -1)
                    {
                        int cha = redValue - a;
                        this.datalist[indexToUpdate].Red = redValue;
                        this.datalist[indexToUpdate].Blue = a;
                        if (this.datalist[indexToUpdate].Time == 1)
                        {
                            this.datalist[indexToUpdate].Cha = 0;
                        }
                        else
                        {
                            this.datalist[indexToUpdate].Cha = cha;
                        }

                        float zhanyoulv = 0;

                        var shijizhi = 0f;
                        var jisuanzhi = 0f;

                        //if (this.datalist[indexToUpdate].SrcData == "156")
                        //{
                        //    var aa = 0;
                        //}

                        if (this.datalist[indexToUpdate].Interval != 0)
                        {
                            shijizhi = Convert.ToSingle(this.datalist[indexToUpdate].ChaZhi) / Convert.ToSingle(this.datalist[indexToUpdate].Interval);
                            jisuanzhi = Convert.ToSingle(this.datalist[indexToUpdate].ChaZhi) / Convert.ToSingle(this.datalist[indexToUpdate].Blue);
                            var jisuancha = Math.Abs(jisuanzhi - shijizhi);

                            if (shijizhi > jisuanzhi)//如果实际值>计算值
                            {
                                zhanyoulv = shijizhi != 0 ? shijizhi - jisuancha * (jisuancha / shijizhi) : 0;
                            }
                            else
                            {
                                zhanyoulv = shijizhi != 0 ? shijizhi + jisuancha * (jisuancha / shijizhi) : 0;
                            }
                        }
                       
                        this.datalist[indexToUpdate].Zhanyoulv = (zhanyoulv*100);


                    }
                }

                // pointlist.Add(new mypoint(xValue, Convert.ToInt32(average).ToString(), redValue));
            }

            // 计算新的统计值
            //CalculateNewStatistics();
        }

        /// <summary>
        /// 计算新的统计值：理论间隔、Z值、新数据间隔Y、新末端差X、差值
        /// </summary>
        private void CalculateNewStatistics()
        {
            if (this.list == null || this.list.Count == 0) return;

            // 按出现次数分组
            var groupedByTime = this.list.GroupBy(item => item.Time);

            foreach (var timeGroup in groupedByTime)
            {
                int N = timeGroup.Key; // 出现次数
                if( N == 7)
                {
                    Console.WriteLine("KEY = " + N);
                }

                Console.WriteLine("KEY = " + N);
                float theoreticalInterval = MaxCount / (float)(N + 1); // 理论间隔 = 总数据数 / (N+1)

                // 按理论分隔线分组：小于理论值的为B组，大于理论值的为A组
                var groupA = timeGroup.Where(item => item.Interval > theoreticalInterval).ToList(); // 大于理论值组
                var groupB = timeGroup.Where(item => item.Interval < theoreticalInterval).ToList(); // 小于等于理论值组

                // 计算A组和B组的末端差均值
                float avgEndDiffA = groupA.Count > 0 ? (float)groupA.Average(item => item.DataEndDiff) : 0;
                float avgEndDiffB = groupB.Count > 0 ? (float)groupB.Average(item => item.DataEndDiff) : 0;

                // 计算X值：末端差大小均值 = (A组均值 + B组均值) / 2
                float X = 0;
                if (groupA.Count == 0)
                {
                    X = avgEndDiffB;
                }
                else if (groupB.Count == 0)
                {
                    X = avgEndDiffA ;

                }
                else {
                    X = (avgEndDiffA + avgEndDiffB) / 2;
                }
                    

                // 修正Y值计算：按末端差正负值分组
                // M组：末端差小于0的数据
                var groupM = timeGroup.Where(item => item.DataEndDiff < 0).ToList();
                // N组：末端差大于0的数据
                var groupN = timeGroup.Where(item => item.DataEndDiff > 0).ToList();

                // 计算M组和N组的数据间隔均值
                float avgM = groupM.Count > 0 ? (float)groupM.Average(item => item.Interval) : 0;
                float avgN = groupN.Count > 0 ? (float)groupN.Average(item => item.Interval) : 0;

                // 计算Y值：间隔正负均值 = (M组间隔均值 + N组间隔均值) / 2
                float Y = 0;
                if (groupM.Count != 0 && groupN.Count != 0)
                {
                    Y = (avgM + avgN) / 2;
                }
                else if (groupM.Count == 0) {
                    Y = avgN;
                }
                else if (groupN.Count == 0)
                {
                    Y = avgM;
                }
                

                // 计算Z值 = Y + (X/2)
                float Z = Y + (X / 2);

                // 计算差值 = 理论间隔 - Z值
                float diffValue = theoreticalInterval - Z;

                // 标记异常值：A组中末端差为负值的、B组中末端差为正值的
                foreach (var item in groupA)
                {
                    if (item.DataEndDiff > 0)
                        item.IsAnomalyValue = true;
                }
                foreach (var item in groupB)
                {
                    if (item.DataEndDiff < 0)
                        item.IsAnomalyValue = true;
                }

                // 获取输入框X值
                float inputXValue = 0;
                bool hasInputValue = false;
                if (this.InvokeRequired)
                {
                    this.Invoke(new System.Action(() =>
                    {
                        hasInputValue = float.TryParse(textBoxXValue.Text, out inputXValue) && !string.IsNullOrWhiteSpace(textBoxXValue.Text);
                    }));
                }
                else
                {
                    hasInputValue = float.TryParse(textBoxXValue.Text, out inputXValue) && !string.IsNullOrWhiteSpace(textBoxXValue.Text);
                }

                // 更新每个数据项的统计值
                foreach (var item in timeGroup)
                {
                    if (item.SrcData == "571") {
                        Console.WriteLine();
                    }
                    item.TheoreticalInterval = theoreticalInterval;
                    item.ZValue = Z;
                    item.NewDataIntervalY = Y;
                    item.NewEndDiffX = X;
                    item.DiffValue = diffValue;
                    // 计算列X：如果输入框有值则使用 X-(z值*次数+理论间隔)，否则使用 z值*次数+理论间隔
                    if (hasInputValue)
                    {
                        item.ColumnX = inputXValue - (Z * N + theoreticalInterval);
                    }
                    else
                    {
                        item.ColumnX = Z * N + theoreticalInterval;
                    }
                }
            }
        }

        /// <summary>
        /// 剔除异常值
        /// </summary>
        private void RemoveAnomalyValues()
        {
            if (this.datalist == null || this.datalist.Count == 0) return;

            // 收集被删除的异常数据
            List<Data> deletedAnomalyData = new List<Data>();
            DataList list = new DataList();
            
            for (int i = this.datalist.Count - 1; i >= 0; i--)
            {
                if (!this.datalist[i].IsAnomalyValue)
                {
                    list.Add(this.datalist[i]);
                }
                else {
                    // 创建删除数据的副本，避免引用问题
                    Data deletedData = new Data();
                    deletedData.SrcData = this.datalist[i].SrcData;
                    deletedData.Time = this.datalist[i].Time;
                    deletedData.Interval = this.datalist[i].Interval;
                    deletedData.Zhanyoulv = this.datalist[i].Zhanyoulv;
                    deletedData.TheoreticalInterval = this.datalist[i].TheoreticalInterval;
                    deletedData.ZValue = this.datalist[i].ZValue;
                    deletedData.DiffValue = this.datalist[i].DiffValue;
                    deletedData.IsAnomalyValue = this.datalist[i].IsAnomalyValue;
                    // CurrentRawDataList是静态属性，不需要复制
                    
                    deletedAnomalyData.Add(deletedData);
                }
            }

            this.showData(list);

            // 如果有删除的数据，显示删除数据窗体
            if (deletedAnomalyData.Count > 0)
            {
                FrmDeletedDataDisplay deletedForm = new FrmDeletedDataDisplay(deletedAnomalyData);
                deletedForm.Show();
            }
            
            MessageBox.Show($"已剔除 {deletedAnomalyData.Count} 个异常值");
        }

        /// <summary>
        /// 剔除新异常值（重新标记异常值后剔除）
        /// </summary>
        private void RemoveNewAnomalyValues()
        {
            if (this.datalist == null || this.datalist.Count == 0) return;

            // 重新计算统计值和异常值标记
            CalculateNewStatistics();

            // 收集被删除的新异常数据
            List<Data> deletedNewAnomalyData = new List<Data>();
            
            for (int i = this.datalist.Count - 1; i >= 0; i--)
            {
                if (this.datalist[i].IsAnomalyValue && !this.datalist[i].IsNewAnomalyValue)
                {
                    // 创建删除数据的副本
                    Data deletedData = new Data();
                    deletedData.SrcData = this.datalist[i].SrcData;
                    deletedData.Time = this.datalist[i].Time;
                    deletedData.Interval = this.datalist[i].Interval;
                    deletedData.Zhanyoulv = this.datalist[i].Zhanyoulv;
                    deletedData.TheoreticalInterval = this.datalist[i].TheoreticalInterval;
                    deletedData.ZValue = this.datalist[i].ZValue;
                    deletedData.DiffValue = this.datalist[i].DiffValue;
                    deletedData.IsAnomalyValue = this.datalist[i].IsAnomalyValue;
                    deletedData.IsNewAnomalyValue = true;
                    // CurrentRawDataList是静态属性，不需要复制
                    
                    deletedNewAnomalyData.Add(deletedData);
                    
                    this.datalist[i].IsNewAnomalyValue = true;
                    this.datalist.RemoveAt(i);
                }
            }

            // 重新计算间隔和统计
            this.datalist.CountingInterval();
            ShuaxinLv();

            // 刷新显示
            DataList list = null;
            if (!this.cbshowrepeat.Checked)
            {
                list = this.datalist.MergeSrcData();
            }
            else
            {
                list = this.datalist;
            }
            this.showData(list);

            // 如果有删除的数据，显示删除数据窗体
            if (deletedNewAnomalyData.Count > 0)
            {
                FrmDeletedDataDisplay deletedForm = new FrmDeletedDataDisplay(deletedNewAnomalyData);
                deletedForm.Show();
            }

            MessageBox.Show($"已剔除 {deletedNewAnomalyData.Count} 个新异常值");
        }

        public void showData(DataList list)
        {
            if (list == null) return;
            list.SumByItems = (cbValueSetting.SelectedItem != null) ? ((string)cbValueSetting.SelectedItem).Trim().Split(' ') : new string[] { };
            List<string> strs = new List<string>();



            if (this.chbValueSum.Checked) strs.Add("Sum");
            if (this.chbcishucha.Checked) strs.Add("Cha");
            if (this.chbColumnX.Checked) strs.Add("ColumnX");
            if (this.chbzhanyoulv.Checked) strs.Add("Zhanyoulv");
            if (this.chbDataEndDiff.Checked) strs.Add("DataEndDiff");


            if (this.chbA.Checked) strs.Add("A");
            if (this.chbH.Checked) strs.Add("H");
            if (this.chbB.Checked) strs.Add("B");
           
            if (this.chbAAC2.Checked) strs.Add("AAC2");
            if (this.chbACH2.Checked) strs.Add("ACH2");
            if (this.chbABG2.Checked) strs.Add("ABG2");

            if (this.chbBAC2.Checked) strs.Add("BAC2");
            if (this.chbBGH2.Checked) strs.Add("BGH2");
            if (this.chbBBG2.Checked) strs.Add("BBG2");

            if (this.chbA1.Checked) strs.Add("A1");
            if (this.chbA2.Checked) strs.Add("A2");
            if (this.chbA3.Checked) strs.Add("A3");
            if (this.chbA4.Checked) strs.Add("A4");
            if (this.chbA5.Checked) strs.Add("A5");
            if (this.chbA6.Checked) strs.Add("A6");
            if (this.chbB1.Checked) strs.Add("B1");
            if (this.chbB2.Checked) strs.Add("B2");
            if (this.chbB3.Checked) strs.Add("B3");
            if (this.chbB4.Checked) strs.Add("B4");
            if (this.chbB5.Checked) strs.Add("B5");
            if (this.chbB6.Checked) strs.Add("B6");




            list.TotalByItems = strs.ToArray();
            list.RefreshListData();
            foreach (Data data in list)
            {
                data.UpdatePercent();
            }
            this.datalist = list;
            this.ShuaxinLv();


            dataGridView1.DataSource = null;
            dataGridView1.DataSource = this.datalist;
            if (this.isGroupMode)
            {
                dataGridView1.Columns["Time"].Visible = false;
                dataGridView1.Columns["Interval"].Visible = false;
                dataGridView1.Columns["Deviation"].Visible = false;
            }
            else
            {
                dataGridView1.Columns["Time"].Visible = true;
                dataGridView1.Columns["Interval"].Visible = true;
                dataGridView1.Columns["Deviation"].Visible = true;
            }
            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.Automatic;
                col.HeaderCell.SortGlyphDirection = SortOrder.None;
            }
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridView1.Refresh();
            label3.Text = "总平均间隔:" + (dataGridView1.DataSource as DataList).CountingAverageInterval(this.cbshowrepeat.Checked).ToString();
        }



        private Thread thread;

        //public void ShuaxinCha()
        //{
        //    // 如果 thread 不为空并且任务仍在执行，则取消任务
        //    if (thread != null && thread.IsAlive)
        //    {
        //        thread.Abort(); // 终止前一个线程
        //                        // 等待一小段时间，确保前一个线程已经结束
        //        Thread.Sleep(100);
        //    }

        //    // 创建新的线程执行 ShuaxinTread 方法
        //    thread = new Thread(new ThreadStart(ShuaxinTread));
        //    thread.Start();
        //}

        private void ShuaxinCha()
        {
            // 更新数据绑定
            dataGridView1.Invoke((MethodInvoker)delegate
            {
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = datalist;
                // dataGridView1.InvalidateColumn(8); // 使列无效，触发重绘
                dataGridView1.Update();
            });
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void chbValueSum_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void chbBGH3_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button18_Click(object sender, EventArgs e)
        {
            button18.Enabled = false;
            saveFileDialog1.Filter = "xlsx文件|*.xlsx";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string file = saveFileDialog1.FileName;
                // 创建一个新的线程来执行导出操作
                Thread exportThread = new Thread(() =>
            {
                ExportToExcel(dataGridView1,file);
                button18.Invoke(new System.Action(() => { button18.Enabled = true; }));
            });

            // 设置线程为后台线程，当主线程退出时，后台线程也会退出
            exportThread.IsBackground = true;

            // 启动线程
            exportThread.Start();
            }
        }

        private void ExportToExcel(DataGridView dataGridView,string file)
        {
                try
                {
                    // 创建一个新的 Excel 应用程序
                    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                    //excelApp.Visible = true; // 使 Excel 可见

                    // 创建一个新的工作簿
                    Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
                    // 创建一个新的工作表
                    Worksheet worksheet = workbook.Sheets[1];

                    // 将 DataGridView 控件中的数据复制到 Excel 工作表中
                    for (int i = 0; i < dataGridView.Rows.Count; i++)
                    {
                        for (int j = 0; j < dataGridView.Columns.Count; j++)
                        {
                            worksheet.Cells[i + 1, j + 1] = dataGridView.Rows[i].Cells[j].Value.ToString();
                        }
                    }

                    // 保存工作簿
                    workbook.SaveAs(file);
                    workbook.Close();
                    excelApp.Quit();

                    MessageBox.Show("数据已成功导出到 Excel 文件！");
                }
            catch (Exception ex)
            {
                MessageBox.Show("导出 Excel 文件时出错：" + ex.Message);
            }
       
           
        }



        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void button19_Click(object sender, EventArgs e)
        {
            // 导出
            saveFileDialog1.Filter = "txt文件|*.txt";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string file = saveFileDialog1.FileName;
                File.Delete(file);
                FileStream fsw = new FileStream(file, FileMode.Create);
                StreamWriter sw = new StreamWriter(fsw, Encoding.Default);
                DataList list = dataGridView1.DataSource as DataList;
                if (list == null)
                {
                    return;
                }


               
                for (int i = 0; i < list.Count; i++)
                {
                  
                        var d = list[i].Deviation;

                    string ds = "";
                        for (int j = 0; j < d.Count; j++)
                        {
                        ds = string.Join("-", d);
                        }
                    sw.WriteLine(ds);
                }
                sw.Close();
                fsw.Close();
                MessageBox.Show("导出成功!");
            }
        }

        private void chbChazhi_CheckedChanged(object sender, EventArgs e)
        {
            chbChazhi.Enabled = false;

            thread = new Thread(new ThreadStart(ShuaxinTread));
            thread.Start();

            
            //chbChazhi.Visible = true;
        }

        //}

        private void ShuaxinTread()
        {
            if (this.datalist == null)
            {
                chbChazhi.Invoke(new System.Action(() => { chbChazhi.Enabled = true; }));
                return;
            }
            if (chbChazhi.Checked)
            {

                foreach (var m in this.datalist)
                {
                    m.Cha = m.Blue - m.Red;
                }
                //from1.showData(from1.datalist);
                this.ShuaxinCha();
            }
            else
            {

                foreach (var m in this.datalist)
                {
                    m.Cha = m.Red - m.Blue;
                }
                this.ShuaxinCha();
                // from1.showData(from1.datalist);
            }
            chbChazhi.Invoke(new System.Action(() => { chbChazhi.Enabled = true; }));
        }

        private void cbValueSetting_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button20_Click(object sender, EventArgs e)
        {
            string[] t1 = richTextBox1.Text.Trim().Split(' ');
            if (t1.Length < 2)
            {
                MessageBox.Show("请先导入至少两位数据", "提示");
                return;
            }
            savefile.Filter = "csv文件|*.csv";
            if (savefile.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (File.Exists(savefile.FileName)) File.Delete(savefile.FileName);
                    FileStream fsw = new FileStream(savefile.FileName, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fsw, Encoding.Default);


                    int tempA = 0;
                    for (int i=0;i<t1.Length; i++)
                    {

                        if (i % 2==0)
                        {
                            tempA = Convert.ToInt32(t1[i]);
                        }
                        else
                        {
                            int zhi = (tempA ^ Convert.ToInt32(t1[i]));
                            string a = "";
                            string zhistr = zhi.ToString();
                            if (zhistr.Length == 1)
                            {
                                zhistr = "00" + zhistr;
                            }else if (zhistr.Length == 2)
                            {
                                zhistr = "0" + zhistr;
                            }else if (zhistr.Length > 3)
                            {
                                zhistr = "000";
                            }
                            a += string.Join(",",zhistr.ToCharArray());
                            sw.WriteLine(a);
                        }
                    }


                    sw.Close();
                    fsw.Close();
                    MessageBox.Show("导出完成！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void labelMax_Click(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void chkAutoStatMode_CheckedChanged(object sender, EventArgs e)
        {
            isAutoStatMode = chkAutoStatMode.Checked;
            btnStartAutoStat.Enabled = isAutoStatMode;
            labelAutoStatCount.Enabled = isAutoStatMode;
            textBoxAutoStatCount.Enabled = isAutoStatMode;
            btnShowAutoStatPic.Enabled = isAutoStatMode;
            // 可选：弹窗提示
            // MessageBox.Show(isAutoStatMode ? "自动统计模式已开启" : "自动统计模式已关闭");
        }

        private void textBoxManualPercent_TextChanged(object sender, EventArgs e)
        {
            float percent = 0.0f;
            if (float.TryParse(textBoxManualPercent.Text.Trim(), out percent))
            {
                Com.Data.ManualInputPercent = percent / 100.0f; // 转换为小数形式
            }
            else
            {
                Com.Data.ManualInputPercent = 0.0f;
            }
        }

        // 获取所有截图部分勾选的Data字段名
        private List<string> GetCheckedStatFieldNames()
        {
            var checkedFields = new List<string>();
            if (chbA.Checked) checkedFields.Add("Ac");
            if (chbH.Checked) checkedFields.Add("H");
            if (chbB.Checked) checkedFields.Add("Bg");
            if (chbAAC2.Checked) checkedFields.Add("AAc2");
            if (chbACH2.Checked) checkedFields.Add("Ach2");
            if (chbABG2.Checked) checkedFields.Add("ABg2");
            if (chbBAC2.Checked) checkedFields.Add("BAc2");
            if (chbBGH2.Checked) checkedFields.Add("Bgh2");
            if (chbBBG2.Checked) checkedFields.Add("BBg2");
            if (chbA1.Checked) checkedFields.Add("A1");
            if (chbA2.Checked) checkedFields.Add("A2");
            if (chbA3.Checked) checkedFields.Add("A3");
            if (chbA4.Checked) checkedFields.Add("A4");
            if (chbA5.Checked) checkedFields.Add("A5");
            if (chbA6.Checked) checkedFields.Add("A6");
            if (chbB1.Checked) checkedFields.Add("B1");
            if (chbB2.Checked) checkedFields.Add("B2");
            if (chbB3.Checked) checkedFields.Add("B3");
            if (chbB4.Checked) checkedFields.Add("B4");
            if (chbB5.Checked) checkedFields.Add("B5");
            if (chbB6.Checked) checkedFields.Add("B6");
            return checkedFields;
        }

        /// <summary>
        /// 将排序后的数据写入Excel工作表
        /// </summary>
        /// <param name="worksheet">Excel工作表</param>
        /// <param name="sortedData">排序后的数据列表</param>
        /// <param name="sheetName">工作表名称</param>
        /// <param name="columns">DataGridView的列集合</param>
        private void WriteDataToExcelSheet(Worksheet worksheet, List<Data> sortedData, string sheetName, DataGridViewColumnCollection columns)
        {
            try
            {
                worksheet.Name = sheetName;
                int rowCount = sortedData.Count;
                int colCount = columns.Count;
                object[,] dataArr = new object[rowCount + 1, colCount];

                // 表头
                for (int j = 0; j < colCount; j++)
                    dataArr[0, j] = columns[j].HeaderText;

                // 数据
                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = 0; j < colCount; j++)
                    {
                        var prop = sortedData[i].GetType().GetProperty(columns[j].DataPropertyName);
                        dataArr[i + 1, j] = prop != null ? prop.GetValue(sortedData[i], null)?.ToString() ?? "" : "";
                    }
                }

                // 一次性写入
                var range = worksheet.Range[
                    worksheet.Cells[1, 1],
                    worksheet.Cells[rowCount + 1, colCount]
                ];
                range.Value2 = dataArr;

                worksheet.Columns.AutoFit();
            }
            catch (Exception ex)
            {
                throw new Exception($"写入Excel工作表时发生错误: {ex.Message}", ex);
            }
        }

        private void btnStartAutoStat_Click(object sender, EventArgs e)
        {
            // 禁用按钮，防止重复点击
            btnStartAutoStat.Enabled = false;
            
            // 1. 检查richTextBox1中是否有数据
            string rawData = richTextBox1.Text.Trim();
            if (string.IsNullOrEmpty(rawData))
            {
                MessageBox.Show("请先设置导入数据", "提示");
                btnStartAutoStat.Enabled = true;
                btnStartAutoStat.Text = "开始自动统计";
                return;
            }
            // 2. 检查textBoxAutoStatCount是否输入了一个大于0的值
            int statCount = 0;
            if (!int.TryParse(textBoxAutoStatCount.Text.Trim(), out statCount) || statCount <= 0)
            {
                MessageBox.Show("请输入大于0的统计次数", "提示");
                btnStartAutoStat.Enabled = true;
                btnStartAutoStat.Text = "开始自动统计";
                return;
            }

            // 获取当前选择的排序列（在主线程中获取）
            string selectedColumn = cbSortColumn.SelectedItem.ToString();

            // 获取是否写入Excel的选项
            bool writeExcel = chkWriteExcel.Checked;

            // 声明Excel相关变量和数据收集变量（在try-catch块外部）
            Microsoft.Office.Interop.Excel.Application excelApp = null;
            Workbook workbook = null;
            List<Data> allDeletedData = new List<Data>(); // 收集所有删除的数据
            
            // 创建后台线程执行计算
            Thread calculationThread = new Thread(() =>
            {
                try
                {
                    // 3. 删除最后一个数据并导入
                    string[] dataArr = rawData.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (dataArr.Length <= 1)
                    {
                        this.Invoke(new System.Action(() =>
                        {
                            MessageBox.Show("数据量不足，无法删除最后一个数据", "提示");
                            btnStartAutoStat.Enabled = true;
                            btnStartAutoStat.Text = "开始自动统计";
                        }));
                        return;
                    }

                    string deletedFirst = dataArr[dataArr.Length - 1];
                    string[] newDataArr = dataArr.Take(dataArr.Length - 1).ToArray();
                    
                    // 在UI线程中更新richTextBox1
                    this.Invoke(new System.Action(() =>
                    {
                        daoru_process(newDataArr);
                        richTextBox1.Text = string.Join(" ", newDataArr);
                        btnStartAutoStat.Text = "正在处理第1次循环";
                    }));

                    // 对表格数据排序（使用选择的排序列）
                    if (this.datalist != null && this.datalist.Count > 0)
                    {
                        string sortField = GetPropertyNameFromDisplayName(selectedColumn);
                        var sorted = this.datalist.OrderBy(d =>
                        {
                            var prop = d.GetType().GetProperty(sortField);
                            return prop != null ? Convert.ToDouble(prop.GetValue(d, null)) : 0;
                        })
                        .ThenBy(d => d.Zhanyoulv)
                        .ToList();

        

                        var newList = new DataList();
                        foreach (var item in sorted)
                            newList.Add(item);
                        this.datalist = newList;
                        
                        // 在UI线程中更新显示
                        this.Invoke(new System.Action(() =>
                        {
                            this.showData(this.datalist);
                        }));

                        // 找到刚删除的数据在排序后列表中的序号
                        autoStatDeletedIndexList.Clear();
                        int idx = sorted.FindIndex(d => d.SrcData == deletedFirst);
                        Console.WriteLine($"删除的数据：{deletedFirst},位置为{idx}");

                        // 如果需要写入Excel，初始化Excel应用程序和工作簿
                        if (writeExcel)
                        {
                            excelApp = new Microsoft.Office.Interop.Excel.Application();
                            workbook = excelApp.Workbooks.Add();
                        }
                        if (idx != -1)
                        {
                            // 将第一次删除的数据添加到集合中
                            allDeletedData.Add(sorted[idx]);
                            autoStatDeletedIndexList.Add(idx);
                            if (delDatas.ContainsKey(idx))
                            {
                                string deleteStr = "";
                                delDatas.TryGetValue(idx, out deleteStr);
                                delDatas.Remove(idx);
                                delDatas.Add(idx, deletedFirst + " " + deleteStr);
                            }
                            else
                            {
                                delDatas.Add(idx, deletedFirst);
                            }
                        }
                    }

                    // 临时保存第一次统计后的数据（深拷贝）
                    autoStatFirstData = new Dictionary<string, double>();
                    foreach (var d in this.datalist)
                    {
                        autoStatFirstData[d.SrcData] = d.Total;
                    }
                    dataArr = newDataArr;

                    // 后续自动统计循环
                    for (int i = 0; i < statCount - 1; i++) // 已经做过一次，继续statCount-1次
                    {
                        if (dataArr.Length <= 1) break;
                        string deleted = dataArr[dataArr.Length - 1];
                        newDataArr = dataArr.Take(dataArr.Length - 1).ToArray();
                        
                        // 在UI线程中更新显示
                        this.Invoke(new System.Action(() =>
                        {
                            daoru_process(newDataArr);
                            richTextBox1.Text = string.Join(" ", newDataArr);
                            btnStartAutoStat.Text = $"正在处理第{i + 2}次循环";
                        }));

                        // 排序（使用选择的排序列）
                        if (this.datalist != null && this.datalist.Count > 0)
                        {
                            string sortField = GetPropertyNameFromDisplayName(selectedColumn);
                            var sorted = this.datalist.OrderBy(d =>
                            {
                                var prop = d.GetType().GetProperty(sortField);
                                return prop != null ? Convert.ToDouble(prop.GetValue(d, null)) : 0;
                            })
                            .ThenBy(d => d.Zhanyoulv)
                            .ToList();


                            var newList = new DataList();
                            foreach (var item in sorted)
                                newList.Add(item);
                            this.datalist = newList;
                            
                            // 在UI线程中更新显示
                            this.Invoke(new System.Action(() =>
                            {
                                this.showData(this.datalist);
                            }));

                            // 找到刚删除的数据在排序后列表中的序号
                            int idx = sorted.FindIndex(d => d.SrcData == deleted);
                            Console.WriteLine($"删除的数据：{deleted},位置为{idx}");
                            if (idx == -1) {
                                continue;
                            }
                            // 将删除的数据添加到集合中
                            allDeletedData.Add(sorted[idx]);
                            autoStatDeletedIndexList.Add(idx);
                            if (delDatas.ContainsKey(idx))
                            {
                                string deleteStr = "";
                                delDatas.TryGetValue(idx, out deleteStr);
                                delDatas.Remove(idx);
                                delDatas.Add(idx, deleted + " " + deleteStr);
                            }
                            else
                            {
                                delDatas.Add(idx, deleted);
                            }
                        }
                        dataArr = newDataArr;
                    }

                    // 保存Excel文件（如果需要）
                    if (writeExcel && workbook != null && excelApp != null && allDeletedData != null && allDeletedData.Count > 0)
                    {
                        try
                        {
                            // 将所有删除的数据写入到第一个工作表中
                            WriteDataToExcelSheet(workbook.Sheets[1], allDeletedData, "自动统计删除的数据", dataGridView1.Columns);
                            
                            // 保存Excel文件
                            string excelPath = Path.Combine(Application.StartupPath, $"自动统计结果_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx");
                            workbook.SaveAs(excelPath);
                            workbook.Close();
                            excelApp.Quit();
                        }
                        catch (Exception excelEx)
                        {
                            this.Invoke(new System.Action(() =>
                            {
                                MessageBox.Show($"保存Excel文件时发生错误: {excelEx.Message}", "错误");
                            }));
                        }
                    }

                    // 在UI线程中显示统计图
                    this.Invoke(new System.Action(() =>
                    {
                        btnShowAutoStatPic_Click(null, null);
                        btnStartAutoStat.Enabled = true;
                        btnStartAutoStat.Text = "开始自动统计";
                        if (writeExcel)
                        {
                            MessageBox.Show("Excel文件已保存到程序目录", "提示");
                        }
                    }));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.WriteLine(ex.StackTrace);
                    
                    // 确保Excel应用程序被正确关闭
                    if (writeExcel && workbook != null && excelApp != null)
                    {
                        try
                        {
                            workbook.Close(false);
                            excelApp.Quit();
                        }
                        catch { /* 忽略清理时的异常 */ }
                    }
                    
                    this.Invoke(new System.Action(() =>
                    {
                        MessageBox.Show("自动统计过程中发生错误：" + ex.Message, "错误");
                        btnStartAutoStat.Enabled = true;
                        btnStartAutoStat.Text = "开始自动统计";
                    }));
                }
            });

            // 设置线程为后台线程
            calculationThread.IsBackground = true;
            // 启动线程
            calculationThread.Start();
        }

        private void btnShowAutoStatPic_Click(object sender, EventArgs e)
        {
            if (autoStatFirstData == null || autoStatFirstData.Count == 0)
            {
                MessageBox.Show("没有可用的自动统计图像数据，请先进行自动统计！", "提示");
                return;
            }
            FrmShowTotal autoStatForm = new FrmShowTotal();
            autoStatForm.Data.Clear();
            // 先填充底图数据
            foreach (var kvp in autoStatFirstData)
            {
                if (!autoStatForm.Data.ContainsKey(kvp.Key))
                    autoStatForm.Data.Add(kvp.Key, kvp.Value);
            }
            // 显示窗体前，设置红色柱子
            autoStatForm.Load += (s, args) =>
            {
                // 先清空再绘制
                var chart = autoStatForm.Controls.Find("chartData", true).FirstOrDefault() as System.Windows.Forms.DataVisualization.Charting.Chart;
                if (chart != null)
                {
                    // 设置搜索文本
                    string searchText = "";
                    // 找出数据中的最大值
                    double maxValue = chart.Series[0].Points.Max(p => p.YValues[0]);
                    
                    // 创建一个列表保存被删除数据的值和位置
                    List<string> deletedValues = new List<string>();
                    
                    for (int i = 0; i < chart.Series[0].Points.Count; i++)
                    {
                        if (autoStatDeletedIndexList.Contains(i))
                        {
                            // 获取实际的数据值（AxisLabel是柱子的标签，即数据值）
                            //string dataValue = chart.Series[0].Points[i].AxisLabel;
                            string deleteStr = "";
                            delDatas.TryGetValue(i,out deleteStr);
 
                             deletedValues.Add(deleteStr);
                            
                            // 设置红色柱子
                            chart.Series[0].Points[i].Color = Color.Red;
                            chart.Series[0].Points[i].YValues[0] = maxValue; // 设置红色柱子高度为最大值
                            
                            // 在柱子上方添加数据值标签
                            chart.Series[0].Points[i].Label = deleteStr;
                            chart.Series[0].Points[i].LabelForeColor = Color.Red;
                            chart.Series[0].Points[i].LabelBackColor = Color.White;
                            chart.Series[0].Points[i].Font = new System.Drawing.Font(chart.Series[0].Font.FontFamily, 10, FontStyle.Bold);
                            
                            // 添加到搜索文本
                            searchText += deleteStr + " ";
                        }
                        else
                        {
                            chart.Series[0].Points[i].Color = Color.Gainsboro; // 改为更浅的灰色柱子
                            chart.Series[0].Points[i].Label = ""; // 清除非删除数据的标签
                        }
                    }
                    
                    // 设置搜索文本
                    var tbSearchText = autoStatForm.Controls.Find("tbSearchText", true).FirstOrDefault() as System.Windows.Forms.TextBox;
                    if (tbSearchText != null)
                    {
                        tbSearchText.Text = searchText.Trim();
                    }
                    
                    // 设置图表标题包含删除的数据
                    chart.Titles.Clear();
                    chart.Titles.Add(new Title("删除的数据: " + string.Join(", ", deletedValues), Docking.Top));
                    chart.Titles[0].Font = new System.Drawing.Font(chart.Font.FontFamily, 12, FontStyle.Bold);
                }
            };
            autoStatForm.Show();
        }

        private void DataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // Create context menu
                ContextMenuStrip contextMenu = new ContextMenuStrip();
                
                // Add "Sort by this column" option
                ToolStripMenuItem sortItem = new ToolStripMenuItem("用此列数据排序");
                sortItem.Click += (s, args) =>
                {
                    // Use existing sorting functionality
                    dataGridView1.Sort(dataGridView1.Columns[e.ColumnIndex], ListSortDirection.Ascending);
                };
                contextMenu.Items.Add(sortItem);

                // Add "Translate this column" option
                ToolStripMenuItem translateItem = new ToolStripMenuItem("用此列数据翻译");
                translateItem.Click += (s, args) =>
                {
                    // 获取当前列名
                    string colName = dataGridView1.Columns[e.ColumnIndex].DataPropertyName;
                    // 找到"数据"列的索引
                    int dataColIndex = -1;
                    foreach (DataGridViewColumn col in dataGridView1.Columns)
                    {
                        if (col.HeaderText == "数据" || col.DataPropertyName == "SrcData")
                        {
                            dataColIndex = col.Index;
                            break;
                        }
                    }
                    if (dataColIndex == -1)
                    {
                        MessageBox.Show("未找到'数据'列，无法翻译。", "错误");
                        return;
                    }
                    // 构建替换映射
                    Dictionary<string, string> replaceMap = new Dictionary<string, string>();
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (row.IsNewRow) continue;
                        var key = row.Cells[dataColIndex].Value?.ToString();
                        var val = row.Cells[e.ColumnIndex].Value?.ToString();
                        if (!string.IsNullOrEmpty(key) && val != null)
                        {
                            // 尝试解析为小数
                            if (decimal.TryParse(val, out decimal decimalVal))
                            {
                                // 四舍五入到整数
                                val = Math.Round(decimalVal).ToString();
                            }
                            replaceMap[key] = val;
                        }
                    }
                    // 替换 richTextBox1 中的内容
                    var items = richTextBox1.Text.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < items.Length; i++)
                    {
                        if (replaceMap.ContainsKey(items[i]))
                        {
                            var newVal = replaceMap[items[i]] ?? "";
                            if (newVal.Length < 3)
                                newVal = newVal.PadLeft(3, '0');
                            items[i] = newVal;
                        }
                    }
                    richTextBox1.Text = string.Join(" ", items);
                    MessageBox.Show($"已用【{dataGridView1.Columns[e.ColumnIndex].HeaderText}】列数据翻译完成！", "提示");
                };
                contextMenu.Items.Add(translateItem);

                // Show context menu at mouse position
                contextMenu.Show(dataGridView1, dataGridView1.PointToClient(System.Windows.Forms.Cursor.Position));
            }
        }

        // 添加一个辅助方法来将显示名称转换为属性名
        private string GetPropertyNameFromDisplayName(string displayName)
        {
            switch (displayName)
            {
                case "%总和": return "Total";
                case "数据": return "SrcData";
                case "出现次数": return "Time";
                case "次数平均间隔": return "Blue";
                case "数据平均间隔": return "Interval";
                case "数据末端差": return "DataEndDiff";
                case "偏移数据": return "DeviationString";
                case "值相加": return "Sum";
                case "值相加%": return "Sum_percent";
                case "理论间隔": return "TheoreticalInterval";
                case "Z值": return "ZValue";
                case "新数据间隔Y": return "NewDataIntervalY";
                case "新末端差X": return "NewEndDiffX";
                case "次数差": return "Cha";
                case "差值": return "DiffValue";
                case "占有率": return "Zhanyoulv";
                case "A": return "Ac";
                case "A%": return "Ac_percent";
                case "H": return "H";
                case "H%": return "H_percent";
                case "B": return "Bg";
                case "B%": return "Bg_percent";
                case "AAC2": return "AAc2";
                case "AAC2%": return "AAc2_percent";
                case "ACH2": return "Ach2";
                case "ACH2%": return "Ach2_percent";
                case "ABG2": return "ABg2";
                case "ABG2%": return "ABg2_percent";
                case "BAC2": return "BAc2";
                case "BAC2%": return "BAc2_percent";
                case "BGH2": return "Bgh2";
                case "BGH2%": return "Bgh2_percent";
                case "BBG2": return "BBg2";
                case "BBG2%": return "BBg2_percent";
                case "A1": return "A1";
                case "A1%": return "A1_percent";
                case "A2": return "A2";
                case "A2%": return "A2_percent";
                case "A3": return "A3";
                case "A3%": return "A3_percent";
                case "A4": return "A4";
                case "A4%": return "A4_percent";
                case "A5": return "A5";
                case "A5%": return "A5_percent";
                case "A6": return "A6";
                case "A6%": return "A6_percent";
                case "B1": return "B1";
                case "B1%": return "B1_percent";
                case "B2": return "B2";
                case "B2%": return "B2_percent";
                case "B3": return "B3";
                case "B3%": return "B3_percent";
                case "B4": return "B4";
                case "B4%": return "B4_percent";
                case "B5": return "B5";
                case "B5%": return "B5_percent";
                case "B6": return "B6";
                case "B6%": return "B6_percent";
                default: return "Total";
            }
        }

        // 统计前1000行中数据为355的行数及其所在行号
        private void Count355Rows()
        {
            if (datalist == null) { MessageBox.Show("无数据"); return; }
            int count = 0;
            List<int> rowIndexes = new List<int>();
            int max = Math.Min(1000, datalist.Count);
            for (int i = 0; i < max; i++)
            {
                if (datalist[i].SrcData == "355")
                {
                    count++;
                    rowIndexes.Add(i + 1); // 行号从1开始
                }
            }
            MessageBox.Show($"前1000行中，数据为355的有{count}行，分别在第：{string.Join(",", rowIndexes)} 行。", "355统计");
        }

        private void btnRemoveAnomalies_Click(object sender, EventArgs e)
        {
            RemoveAnomalyValues();
        }

        private void btnRemoveNewAnomalies_Click(object sender, EventArgs e)
        {
            RemoveNewAnomalyValues();
        }

        private void btnSetStartPoint_Click(object sender, EventArgs e)
        {
            // 创建并显示设置启动点窗口
            FrmSetStartPoint frmSetStartPoint = new FrmSetStartPoint(this);
            frmSetStartPoint.ShowDialog();
        }

        private void btnRefreshX2_Click(object sender, EventArgs e)
        {
            // 刷新X2列数据
            RefreshX2Data();
        }

        /// <summary>
        /// 刷新X2列数据并更新平均值显示
        /// </summary>
        private void RefreshX2Data()
        {
            if (datalist == null || datalist.Count == 0)
            {
                MessageBox.Show("没有数据可以刷新", "提示");
                return;
            }

            try
            {
                // 重新绑定数据源以触发ColumnX2的重新计算
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = datalist;

                // 计算并更新X2平均值
                UpdateX2Average();

                // 刷新界面
                dataGridView1.Refresh();
                
                MessageBox.Show("X2列数据已刷新", "提示");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新X2数据时发生错误：{ex.Message}", "错误");
            }
        }

        /// <summary>
        /// 计算并更新X2平均值显示
        /// </summary>
        private void UpdateX2Average()
        {
            if (datalist == null || datalist.Count == 0)
            {
                labelX2Average.Text = "X2平均值：0";
                return;
            }

            try
            {
                // 计算所有行X2列数据的平均值
                double sum = 0;
                int count = 0;

                foreach (Data data in datalist)
                {
                    sum += data.ColumnX2;
                    count++;
                }

                double average = count > 0 ? sum / count : 0;
                labelX2Average.Text = $"X2平均值：{average:F4}";
            }
            catch (Exception ex)
            {
                labelX2Average.Text = "X2平均值：计算错误";
                Console.WriteLine($"计算X2平均值时发生错误：{ex.Message}");
            }
        }
    }
}
